//
//  recommendWorksDetailViewController.m
//  Wedding fantastic
//
//  Created by dllo on 15/7/2.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "recommendWorksDetailViewController.h"
#import "AFNetworking.h"
#import "recommendWorksDetailCell.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD.h"

@interface recommendWorksDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

// tableview
@property(nonatomic, retain)UITableView *tableView;
// header
@property(nonatomic, retain)UIView *headerView;
// imageView
@property(nonatomic, retain)UIImageView *imageView;

@end

@implementation recommendWorksDetailViewController
- (void)dealloc {
    [_tableView release];
    [_headerView release];
    [_bID release];
    [_recommendWorksInf release];
    [_merchantNameLabel release];
    [_titleLabel release];
    [_describeLabel release];
    [_imageView release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"案例";
    // 导航栏透明
    self.navigationController.navigationBar.translucent = NO;
    
    // 解析数据
    [self createRecommendWorksDetail];
    
    //tableview
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 64 * kHeight / 667 - 49 * kHeight / 667) style:UITableViewStylePlain];
    // 设置代理人
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    // headerview
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    self.headerView.backgroundColor = [UIColor colorWithRed:241 / 255.0 green:241 / 255.0 blue:240 / 255.0 alpha:1];
    self.tableView.tableHeaderView = self.headerView;
    [self.headerView release];
    // iamgeview
    // 把图片加到header上
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.headerView.frame.size.width, self.headerView.frame.size.height - 50 * kHeight / 667)];
    [self.headerView addSubview:self.imageView];
    // 创建需要的毛玻璃特效类型
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight & UIBlurEffectStyleLight];
    // 毛玻璃view视图
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    // 添加到有毛玻璃特效的控件上
    effectView.frame = self.imageView.bounds;
    [self.imageView addSubview:effectView];
    // 设置模糊透明度
    effectView.alpha = 0.7;
    
    // 商家名称标签
    self.merchantNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(5 * kWidth / 375, 90 * kHeight / 667, self.imageView.frame.size.width - 5 * kWidth / 375, 30 * kWidth / 375)];
    [self.imageView addSubview:self.merchantNameLabel];
    // 设置字体颜色
    self.merchantNameLabel.textColor = [UIColor grayColor];
    [self.merchantNameLabel release];
    
    // 图片标题标签
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 * kWidth / 375, 120 * kHeight / 667, self.imageView.frame.size.width - 10 * kWidth / 375, 30 * kHeight / 667)];
    [self.imageView addSubview:self.titleLabel];
    self.titleLabel.textColor = [UIColor grayColor];
    [_titleLabel release];
    
    // 图片描述标签
    self.describeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 * kWidth / 375, self.imageView.frame.size.height, kWidth - 40 * kWidth / 375, 50 * kHeight / 667)];
    [self.headerView addSubview:self.describeLabel];
    [_describeLabel release];
    
    
    // 回到顶部button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(300 * kWidth / 375, 450 * kHeight / 667, 35 * kWidth / 375, 38 * kHeight / 667);
    [button setBackgroundImage:[UIImage imageNamed:@"backTop"] forState:UIControlStateNormal];
    button.alpha = 0.6;
    [self.view addSubview:button];
    [button addTarget:self action:@selector(backTop:) forControlEvents:UIControlEventTouchUpInside];
    
    // 刷新头部
    [self addHeader];
}
// 刷新头部
- (void)addHeader
{
    __block recommendWorksDetailViewController *detailVC = self;
    
    // 添加下拉刷新头部控件
    [self.tableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        detailVC.page = 1;
        //标记为下拉操作
        detailVC.Loading = NO;
        //重新请求数据
        [self createRecommendWorksDetail];
        
    }];
#pragma mark 自动刷新(一进入程序就下拉刷新)
//    [self.tableView headerBeginRefreshing];
}
// 回到顶部
- (void)backTop:(UIButton *)button
{
    [self.tableView setContentOffset:CGPointZero animated:YES];
}
// tableview的方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  [self.recommendWorksInf media_items].count;
}
// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    // 自定义cell
    recommendWorksDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[recommendWorksDetailCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
    }
    // 给每个cell添加对应的图片
    for (NSInteger i = 0; i < [self.recommendWorksInf media_items].count; i++) {
        if (i == indexPath.row) {
            recommendWorksModel *model = self.recommendWorksInf;
            NSMutableArray *media_itemsArr = [model media_items];
         
            NSString *str = media_itemsArr[i][@"media_path"];
            
            [cell.myImageView sd_setImageWithURL:[NSURL URLWithString: str]];
            
        }
    }
    
    
    
    return  cell;
}
// cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    CGFloat heightX = 0;
    // 获取每个cell的图片高度
//    for (NSInteger i = 0; i < [self.recommendWorksInf media_items].count; i++) {
//        if (i == indexPath.row) {
//            recommendWorksModel *model = self.recommendWorksInf;
//            NSMutableArray *media_itemsArr = [model media_items];
//            
//            NSString *width = media_itemsArr[i][@"width"];
//            NSString *height = media_itemsArr[i][@"height"];
////            NSString *media_pathStr = media_itemsArr[i][@"media_path"];
//            // 截取字符串
////            NSString *str = [media_pathStr substringFromIndex:media_pathStr.length - 3];
//            if ([height integerValue] > 0 && [width integerValue] > 0) {
//                self.heighX = ([height integerValue] * kWidth / 375) * kWidth / ([width integerValue] * kHeight / 667);
//            } else {
//                self.heighX = 200 * kHeight / 667;
//            }
//
//            
//        }
//    }
    //    return (kWidth  * kWidth / 375) * 720 / 1080;
//    return self.heighX;
    return 300 * kHeight / 667;
}
// 解析推荐作品详情页面的信息
- (void)createRecommendWorksDetail {
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hub show:YES];
    NSString *url = [NSString stringWithFormat:@"http://www.hunliji.com/v2/api/app/works/%@.json", self.bID];
   
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
    // 让管理类调用get请求
    [manager GET:url parameters:self success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // 如果数据解析成功, 接收数据
        NSMutableDictionary *resultDic = responseObject;
        NSMutableDictionary *workDic = resultDic[@"work"];
        recommendWorksModel *model = [[recommendWorksModel alloc] init];
        [model setValuesForKeysWithDictionary:workDic];
        self.recommendWorksInf = model;
        // 给imageview加图片
        [self.imageView sd_setImageWithURL: workDic[@"cover_path"]];
        // 给商家名称标签赋值
        self.merchantNameLabel.text = workDic[@"merchant"][@"name"];
        // 给图片标题标签赋值
        self.titleLabel.text = workDic[@"title"];
        // 给图片描述标签赋值
        self.describeLabel.text = workDic[@"describe"];
        // 描述标签的文字自适应
        [self wordsFit:self.describeLabel];
        // 重新设置图片描述标签高度
        self.describeLabel.frame = CGRectMake(10 * kWidth / 375, self.imageView.frame.size.height, kWidth - 40 * kWidth / 375, self.describeLabel.frame.size.height);
        // 重新设置header高度
        self.headerView.frame = CGRectMake(0, 0, kWidth, self.imageView.frame.size.height + self.describeLabel.frame.size.height);
        
        //
//        [model release];
        
        //
        [self.tableView reloadData];
        // 加载完成后完成刷新
        [self.tableView headerEndRefreshing];
        //
        [hub hide:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 如果数据解析失败, 显示错误信息
    }];
}
// 文字自适应
- (void)wordsFit :(UILabel *)label{
    // 文字自适应
    // 计算文本的空间,MAXFLOAT为无限大
    CGRect rect = [label.text boundingRectWithSize:CGSizeMake(kWidth - 30 * kWidth / 375, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: label.font} context:nil];
    // 设置UILabel的最大显示行数(=0时不限制)
    label.numberOfLines = 0;
    // 用计算出来的GCSize/GCRect设置UILabel的frame
    label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, rect.size.width, rect.size.height);
    label.frame= CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
}

// 创建视图
- (void)createView {
    // 上部的布景图片
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
